package com.hks.common.handle;

import com.alibaba.fastjson.JSON;
import com.hks.common.constant.StatusCode;
import com.hks.common.utils.ResponseResult;
import com.hks.common.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义的 security 权限不足的异常处理
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    private static final Logger logger = LoggerFactory.getLogger(AccessDeniedHandlerImpl.class);
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //给前端发送消息
        ResponseResult responseResult = new ResponseResult(StatusCode.PERMISSION_EX, "您的权限不足");
        String json = JSON.toJSONString(responseResult);
        logger.error("权限异常：异常信息：{}", accessDeniedException.getMessage());
        WebUtils.renderString(response, json);
    }
}
